<style scoped>
.wraper {
    padding: 0;
    margin-top: -20px;
}

.search {
    padding-bottom: 20px;
}

.search span {
    color: #68777c;
    font-weight: bold;
    padding-right: 18px;
}

.search button {
    background-color: #00a8f7;
    color: #fff;
    margin-left: 8px;
}

.top {
    margin-bottom: 20px;
    border-top: 1px dashed #cccccc;
}

.detail {
    border-top: 1px dashed #cccccc;
}

.wraper .headline {
    position: relative;
    font-size: 12px;
    color: #303134;
    font-weight: bold;
    margin: 10px 0;
    line-height: 32px;
    height: 32px;
}

.wraper .add-agent {
    position: absolute;
    top: 0px;
    right: 30px;
    background-color: #348bf2;
    color: #fff;
}

.iconfont {
    font-size: 14px;
}



/* 分页 start */

.pagestyle {
    margin: 20px 0;
    float:right;
    padding-right: 15px;
}


/* 分页 end */

.leftside{
    overflow-y: auto;
   
}
.leftside-search{
    padding: 20px 25px;
    margin-bottom: 15px;
}
.rightside{
    border-left: 1px solid #e9eaec;
}
.leftside-list{
    overflow-y: auto;
    padding-left: 25px;
    padding-right: 25px;
}
.leftside-listicon{
    margin-left: 10px;
}
.leftside-list ul li{
    padding: 8px;
    cursor: pointer;
    border-radius: 3px;
}
.leftside-list ul li:hover{ 
    background: rgba(64,116,225,0.3);
    color:#4074e1;
    border-right: 4px solid #4074e1;
}
.leftside-list ul li:hover a{
    color:#4074e1;
}
.leftside-list .active,.leftside-list ul li.active:hover{
    background-color: #2e7ee1;
    color:#fff;
}
.leftside-list .active a,.leftside-list ul li.active:hover a{
    color: #fff;
}
.leftside-listspan{
    max-width: 75%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-block;
    vertical-align: bottom;
}
.leftside-edit{
    font-size: 14px;
}
.poptip-ul{
    color: #000;
}
.leftside-list ul li .poptip-ul li:hover{
    background-color: #4074e1;
    color:#fff;
}
.rightside-title{
    padding: 20px;
}
.rightside-title h3{
    display: inline-block;
    font-size: 18px;
    font-weight: normal;
}
.title-total{
    font-size: 14px;
    color: #999;
}
.fr{
    float: right;
}
.rightside-content{
    padding: 20px;
}
.fl{
    float: left;
}
.all{
    float: left;
    margin-left: 70px;
}
</style>
<style>
.leftside-list .ivu-poptip .ivu-poptip-body{
    padding-left: 0 !important;
    padding-right: 0 !important;
}
</style>


<template>
    <div class="member-manage">
        <product-title></product-title>
        <div class="wraper">
            <Row>
                <Col :xs="8" :sm="8" :md="8" :lg="4">
                    <div class="leftside">
                        <div class="leftside-search">
                            <Button type="primary" icon="plus" size="large" long @click="addRole()">新增角色</Button>
                        </div>
                        <div class="leftside-list" :style="leftHeight">
                            <ul>
                                <li v-for="(item,index) in rolelist" :key="item.id" :class="active == index ?'active':''" @click="leftActive(index)">
                                    <Icon type="document-text" class="leftside-listicon"></Icon>
                                    <span class="leftside-listspan">{{item.name}}</span>
                                        <Poptip trigger="hover" placement="bottom" style="margin-left: 8px" width="100%">
                                            <Icon @click.stop="drop" class="leftside-edit" type="ios-plus-outline"></Icon>
                                            <div class="api" slot="content">
                                                <ul class="poptip-ul">
                                                    <li @click.stop="editRole(index)">编辑角色</li>
                                                    <li @click.stop="showAction(index)">设置权限</li>
                                                    <li @click.stop="delRole(index)">删除角色</li>
                                                </ul>
                                            </div>
                                        </Poptip>
                                        <!-- <Dropdown @click="edit($event)" trigger="click" style="margin-left: 20px">                                       
                                            <Icon @click="edit(item.id)" class="leftside-edit" type="ios-plus-outline"></Icon>
                                            <DropdownMenu slot="list">
                                                <DropdownItem :name="item.id" @click="edit(item.id)">编辑角色</DropdownItem>
                                                <DropdownItem :name="item.id" @click="edit(item.id)">设置权限</DropdownItem>
                                                <DropdownItem :name="item.id" @click="edit(item.id)">删除角色</DropdownItem>
                                            </DropdownMenu>
                                        </Dropdown> -->
                                    <!-- <div @click.stop="drop" class="">
                                    </div> -->
                                    
                                    <!--  -->
                                </li>                                                 
                            </ul>
                        </div>
                    </div>
                </Col>
                <Col :xs="14" :sm="14" :md="14" :lg="20">
                    <div class="rightside" :style="rightHeight">
                        <div class="rightside-title">
                            <h3>{{rightTitle}}</h3>
                            <span class="title-total">（{{orgTotal}}个）</span>
                            <!-- <Button type="primary" shape="circle" icon="plus" class="fr" @click="addmember()">添加成员</Button> -->
                        </div>
                        <div class="rightside-content">
                            <Table border ref="selection" :columns="columns4" :data="data1"></Table>
                             <Page class-name="pagestyle" :total="orgTotal" show-total @on-change="pageChange"></Page>
                        </div>
                    </div>
                </Col>
            </Row>
        </div>
        <Modal v-model="showAddModal" :mask-closable='closeable' width="600" title="添加/编辑角色" @on-ok="add()" :loading="loading">
            <Row>
                <Col span="18" offset="1">
                    <Form :model="role" ref="role" :rules="ruleValidate" :label-width="120">                   
                        <Form-item label="角色名称：" prop="name" required>
                            <Input v-model="role.name" placeholder="请输入角色名称"></Input>
                        </Form-item>               
                    </Form>
                </Col>
            </Row>
        </Modal>
        <Modal v-model="showactionModal" :mask-closable='closeable' width="1000" title="添加/编辑权限" @on-ok="addaction"  :loading="loading">
            <Row>
                <Form :model="action" ref="action" :rules="ruleValidate" :label-width="120">    
                    <Col span="18" offset="1">                               
                        <FormItem label="模块：">
                            <CheckboxGroup v-model="action.active">
                                <Checkbox :label="item.id" v-for="item in module" :key="item.id">
                                    <span>{{item.name}}</span>
                                </Checkbox>
                            </CheckboxGroup>
                        </FormItem>
                    </Col>
                    <Col span="4" offset="1">
                        <Button type="primary" @click="moduleAll()">全选</Button>
                        <Button type="ghost" @click="moduleAllRemove()">全不选</Button>
                    </Col>
                    <div v-for="(value,key) in actionlist" :key="key">                    
                        <Col span="18" offset="1"  >
                            <FormItem :label="key+'：'">
                                <CheckboxGroup v-model="action.active">
                                    <Checkbox :label="item.id" v-for="item in value" :key="item.id">
                                        <span>{{item.name}}</span>
                                    </Checkbox>
                                </CheckboxGroup>
                            </FormItem>
                        </Col>
                        <Col span="4" offset="1">
                            <Button type="primary" @click="actionAll(key)">全选</Button>
                            <Button type="ghost" @click="actionAllRemove(key)">全不选</Button>
                        </Col>  
                    </div>             
                </Form>
                
            </Row>
            <div slot="footer">
                <Button type="primary" class="all" @click="allSelect()">全选</Button><Button type="ghost" class="fl" @click="allSelectRemove()">全不选</Button><Button type="primary" @click="addaction()">确定</Button><Button type="ghost" @click="cancel()">取消</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import productTitle from '../../components/productTitle'
import { getOrgByRole,  delOrgRole, getAllOrgList ,getUndistributed , getOrgEmployee ,addOrgEmployee , delOrgEmployee } from '../../api/org'
import { getRoleList , saveRole , updateRole , getAllModule , getAllAction , getRoleOperation , saveRoleOperation , delRole } from '../../api/role'
export default {
    data() {
        return {
            cou:-1,
            visible:false,
            listStyle: {                
                height: '300px'
            },
            role:{
                name:'',
                id:''
            },
            action: {
                active:[]
            },
            orgName:'',
            active:0,
            showAddModal:false,
            showactionModal:false,
            closeable:false,
            loading:true,
            leftHeight: {
                height: '0px'
            },
            rightHeight: {
                height: '0px'
            },
            dataLeft: [
                
            ],
            rightTitle:'',
            page:1,
            orgTotal:0,
            rolelist:[],
            titles:['未分配成员','已选择成员'],
            undistributed:[],
            emplyee:[],
            columns4: [                   
                    {
                        title: '名称',
                        key: 'name',
                        align: 'center',
                    },
                    {
                        title: '电话',
                        key: 'tel',
                        align: 'center',
                    },
                    {
                        title: '设置时间',
                        key: 'create_date',
                        align: 'center',
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 150,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [                                
                                h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    on: {
                                        click: () => {
                                            this.remove(params.row.id)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                    
                ],
                ruleValidate: {
                    name: [
                        { required: true, message: '角色名称不能为空', trigger: 'blur' }
                    ],
                },
                data1: [
                    
                ],
                data2: [
                    
                ],
                targetKeys2: [
                    
                ],
                module:[],
                actionlist:{},
                moduleId:[],
                actionId:[]
                
        }
    },
    components: {
        productTitle
    },
    created() {
        let winHeight = screen.availHeight;
        this.leftHeight.height = (winHeight  - 280 - 32) + 'px';
        this.rightHeight.height = (winHeight - 280) + 'px';
        this.getRoleList()
        this.getModule()
        this.getAction()
    },
    methods: {
        mergeArray(arr1, arr2) { 
            for (var i = 0 ; i < arr1.length ; i ++ ){
                 for(var j = 0 ; j < arr2.length ; j ++ ){
                    if (arr1[i] === arr2[j]){
                        arr1.splice(i,1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
                    }
                 }
             }
            for(var i = 0; i <arr2.length; i++){
                arr1.push(arr2[i]);
            }
             return arr1;
        },
        array_diff(a, b) {  
            for(var i=0;i<b.length;i++){  
                for(var j=0;j<a.length;j++){  
                    if(a[j]==b[i]){  
                        a.splice(j,1);  
                        j=j-1;  
                    }  
                }  
            }   
            return a;  
        },
        allSelect(){
            this.action.active = this.mergeArray(this.action.active,this.moduleId)
            this.action.active = this.mergeArray(this.action.active,this.actionId)
        },
        allSelectRemove(){
            this.action.active = []
        },
        moduleAll() {           
            this.action.active = this.mergeArray(this.action.active,this.moduleId)

        },
        moduleAllRemove(){
            this.action.active = this.array_diff(this.action.active,this.moduleId)
        },
        actionAll(index){
            let _arr = this.actionlist[index]
            let _temparr = []
            for(var i=0;i<_arr.length;i++){
                _temparr.push(_arr[i].id)
            }
            this.action.active = this.mergeArray(this.action.active,_temparr)
        },
        actionAllRemove(index){
            let _arr = this.actionlist[index]
            let _temparr = []
            for(var i=0;i<_arr.length;i++){
                _temparr.push(_arr[i].id)
            }
            this.action.active = this.array_diff(this.action.active,_temparr)
        },
        editRole(index){
            this.showAddModal = true
            this.cou = 1
            this.role.name = this.rolelist[index].name
            this.role.id = this.rolelist[index].id
        },
        addRole(){
            this.showAddModal = true
            this.cou = -1
            this.role.name = ""
            this.role.id =""
        },
        editRank(id){
            this.visible = false;
        },
        delRole(index){
            this.$Modal.confirm({
                title: '提示',
                content: '是否要删除该条记录?',
                onOk: () => {
                    var _param = {
                        role_id:this.rolelist[index].id,
                        p:1
                    }
                    
                    new Promise((resolve,reject)=>{
                        getOrgByRole(_param).then(response=>{
                            if (response.data.err == 0) {
                                if(response.data.data.total){
                                    this.$Message.error({content:'该角色下有对应机构账号，请先删除对应机构账号',duration:3})   
                                }else{
                                    this.delRoleLast(this.rolelist[index].id)
                                }            
                            } else {
                                this.$Message.error('操作失败')                    
                            }
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    })
                },
            }); 
        },
        delRoleLast(id){
            let _param = {
                id:id
            }
            new Promise((resolve,reject)=>{
                delRole(_param).then(response=>{
                    if (response.data.err == 0) {
                        this.$Message.success('操作成功')
                        this.getRoleList()                 
                    } else {
                        this.$Message.error('操作失败')                    
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            })
        },
        edit(id){
            console.log(id)
        },
        drop(){

        },
        
        // 页码改变
        pageChange(page) {
            this.page = page
            this.getRoleList()
        },
        getModule() {
            new Promise((resolve, reject) => {
                getAllModule().then(response => {
                    if (response.data.err == 0) {
                        this.module = response.data.data;
                        for(var i = 0;i<this.module.length;i++){
                            this.moduleId.push(this.module[i].id)
                        }
                    } else {
                        this.$Message.error(response.data.info);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        getAction(){
            new Promise((resolve, reject) => {
                getAllAction().then(response => {
                    if (response.data.err == 0) {
                        this.actionlist = response.data.data;                        
                        for(var key in this.actionlist ){
                            for(var i =0;i<this.actionlist[key].length;i++){
                                this.actionId.push(this.actionlist[key][i].id)
                            }
                        }
                    } else {
                        this.$Message.error(response.data.info);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        //
        showAction(index) {
            this.showactionModal = !this.showactionModal
            this.action.id = this.rolelist[index].id 
            var _param = {
                id:this.rolelist[index].id
            }
            new Promise((resolve, reject) => {
                getRoleOperation(_param).then(response => {
                    console.log(response.data)                   
                    if (response.data.err == 0) {
                        this.action.active = response.data.data
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });     
        },
        addaction(){
            new Promise((resolve, reject) => {
                saveRoleOperation(this.action).then(response => {
                    
                    if (response.data.err == 0) {
                        this.showactionModal = false;
                        this.loading = true;
                        this.getRoleList();
                        this.$Message.success(response.data.info);
                        
                    }else{
                        this.$Message.error(response.data.info);
                        setTimeout(() => {
                            this.loading = false;
                            this.$nextTick(() => {
                                this.loading = true;
                            });
                        }, 2000);
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            });
        },
        add(){
            this.$refs['role'].validate((valid) => {
                if (valid) {
                    this.role.cate =2   
                    if(this.cou == -1){                      
                        new Promise((resolve, reject) => {
                            saveRole(this.role).then(response => {
                                if (response.data.err == 0) {
                                    this.showAddModal = false;
                                    this.loading = true;
                                    this.getRoleList();
                                    this.$Message.success(response.data.info);
                                } else {
                                    this.$Message.error(response.data.info);
                                    setTimeout(() => {
                                        this.loading = false;
                                        this.$nextTick(() => {
                                            this.loading = true;
                                        });
                                    }, 2000);
                                }
                                resolve();
                            }).catch(error => {
                                reject(error);
                            });
                        });
                    }else{
                          
                        new Promise((resolve, reject) => {
                            updateRole(this.role).then(response => {
                                if (response.data.err == 0) {
                                    this.showAddModal = false;
                                    this.loading = true;
                                    this.getRoleList();
                                    this.$Message.success(response.data.info);
                                } else {
                                    this.$Message.error(response.data.info);
                                    setTimeout(() => {
                                        this.loading = false;
                                        this.$nextTick(() => {
                                            this.loading = true;
                                        });
                                    }, 2000);
                                }
                                resolve();
                            }).catch(error => {
                                reject(error);
                            });
                        });
                    }                   
                } else {
                    // 通过loading来阻止modal隐藏，然后手动修改loading来充值确定按钮
                    setTimeout(() => {
                        this.loading = false;
                        this.$nextTick(() => {
                            this.loading = true;
                        });
                    }, 2000);
                }
            })
        },
        getRoleList(){
            var _param = {
                cate:2
            }
            new Promise((resolve,reject)=>{
                getRoleList(_param).then(response=>{
                    if (response.data.err == 0) {
                        this.rolelist =  response.data.data    
                        this.role_id = this.rolelist[0].id
                        this.rightTitle = this.rolelist[0].name             
                    } else {
                                             
                    }
                    resolve(this.getOrgByRole());
                }).catch(error => {
                    reject(error);
                });
            })
        },
        getOrgByRole(){
            let _param = {
                role_id:this.role_id,
                p:this.page
            }
            new Promise((resolve,reject)=>{
                getOrgByRole(_param).then(response=>{
                    if (response.data.err == 0) {
                        this.data1 =  response.data.data.list   
                        this.orgTotal =  response.data.data.total           
                    } else {
                                             
                    }
                    resolve();
                }).catch(error => {
                    reject(error);
                });
            })
        },
        remove(id){
            this.$Modal.confirm({
                title: '提示',
                content: '是否要删除该条记录?',
                onOk: () => {
                    var _param = {
                        oid:id,
                    }
                    new Promise((resolve,reject)=>{
                        delOrgRole(_param).then(response=>{
                            console.log(response.data)
                            if (response.data.err == 0) {
                                this.$Message.success('操作成功')
                                this.getOrgByRole()                 
                            } else {
                                this.$Message.error('操作失败')                    
                            }
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    })
                },
            });                     
        },
        leftActive(index){
            this.active = index
            this.rightTitle = this.rolelist[index].name
            this.role_id = this.rolelist[index].id
            this.page = 1
            this.getOrgByRole()
        },
        cancel(){
            this.showactionModal = false;
            this.action.active = []
        }
    }
}
</script>
